package com.fsserver.facedetection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 人脸检测系统启动类
 * 
 * @author fsserver
 * @since 2024-01-01
 */
@SpringBootApplication
public class FaceDetectionApplication {

    private static final Logger logger = LoggerFactory.getLogger(FaceDetectionApplication.class);

    /**
     * 应用程序主入口
     * 
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        try {
            logger.info("==========================================");
            logger.info("人脸检测系统正在启动...");
            logger.info("==========================================");
            
            // 记录启动参数
            if (args.length > 0) {
                logger.info("启动参数: {}", String.join(" ", args));
            } else {
                logger.info("启动参数: 无");
            }
            
            // 记录系统信息
            logSystemInfo();
            
            // 启动Spring应用
            ConfigurableApplicationContext context = SpringApplication.run(FaceDetectionApplication.class, args);
            
            // 记录应用启动成功信息
            logApplicationStartupInfo(context);
            
            logger.info("==========================================");
            logger.info("人脸检测系统启动成功！");
            logger.info("==========================================");
            
        } catch (Exception e) {
            logger.error("人脸检测系统启动失败！", e);
            System.exit(1);
        }
    }

    /**
     * 记录系统信息
     */
    private static void logSystemInfo() {
        try {
            // Java版本信息
            logger.info("Java版本: {}", System.getProperty("java.version"));
            logger.info("Java厂商: {}", System.getProperty("java.vendor"));
            logger.info("Java虚拟机: {}", System.getProperty("java.vm.name"));
            
            // 操作系统信息
            logger.info("操作系统: {} {}", 
                System.getProperty("os.name"), 
                System.getProperty("os.version"));
            logger.info("系统架构: {}", System.getProperty("os.arch"));
            
            // 内存信息
            Runtime runtime = Runtime.getRuntime();
            long maxMemory = runtime.maxMemory() / 1024 / 1024;
            long totalMemory = runtime.totalMemory() / 1024 / 1024;
            long freeMemory = runtime.freeMemory() / 1024 / 1024;
            logger.info("最大内存: {}MB, 总内存: {}MB, 可用内存: {}MB", 
                maxMemory, totalMemory, freeMemory);
            
            // 网络信息
            try {
                String hostAddress = InetAddress.getLocalHost().getHostAddress();
                String hostName = InetAddress.getLocalHost().getHostName();
                logger.info("主机名: {}, IP地址: {}", hostName, hostAddress);
            } catch (UnknownHostException e) {
                logger.warn("无法获取主机信息: {}", e.getMessage());
            }
            
        } catch (Exception e) {
            logger.warn("记录系统信息时发生异常: {}", e.getMessage());
        }
    }

    /**
     * 记录应用启动信息
     * 
     * @param context Spring应用上下文
     */
    private static void logApplicationStartupInfo(ConfigurableApplicationContext context) {
        try {
            Environment env = context.getEnvironment();
            
            // 应用信息
            String applicationName = env.getProperty("spring.application.name", "face-detection-system");
            String version = env.getProperty("spring.application.version", "1.0.0");
            String profiles = String.join(",", env.getActiveProfiles());
            
            logger.info("应用名称: {}", applicationName);
            logger.info("应用版本: {}", version);
            logger.info("激活环境: {}", profiles.isEmpty() ? "default" : profiles);
            
            // 服务端口信息
            String port = env.getProperty("server.port", "8080");
            String contextPath = env.getProperty("server.servlet.context-path", "");
            String protocol = env.getProperty("server.ssl.key-store") != null ? "https" : "http";
            
            logger.info("服务端口: {}", port);
            logger.info("上下文路径: {}", contextPath.isEmpty() ? "/" : contextPath);
            logger.info("访问协议: {}", protocol);
            
            // 访问地址
            try {
                String hostAddress = InetAddress.getLocalHost().getHostAddress();
                String localAddress = "localhost";
                String accessUrl = String.format("%s://%s:%s%s", protocol, localAddress, port, contextPath);
                String networkUrl = String.format("%s://%s:%s%s", protocol, hostAddress, port, contextPath);
                
                logger.info("本地访问地址: {}", accessUrl);
                logger.info("网络访问地址: {}", networkUrl);
                
                // API文档地址
                if (env.getProperty("springdoc.api-docs.path") != null) {
                    String apiDocsPath = env.getProperty("springdoc.api-docs.path", "/v3/api-docs");
                    logger.info("API文档地址: {}{}", accessUrl, apiDocsPath);
                }
                
                if (env.getProperty("springdoc.swagger-ui.path") != null) {
                    String swaggerPath = env.getProperty("springdoc.swagger-ui.path", "/swagger-ui.html");
                    logger.info("Swagger UI地址: {}{}", accessUrl, swaggerPath);
                }
                
            } catch (UnknownHostException e) {
                logger.warn("无法获取网络访问地址: {}", e.getMessage());
            }
            
            // 数据库信息（如果有）
            String datasourceUrl = env.getProperty("spring.datasource.url");
            if (datasourceUrl != null) {
                logger.info("数据库连接: {}", maskSensitiveInfo(datasourceUrl));
            }
            
            // OpenCV信息
            String opencvVersion = System.getProperty("opencv.version");
            if (opencvVersion != null) {
                logger.info("OpenCV版本: {}", opencvVersion);
            }
            
        } catch (Exception e) {
            logger.warn("记录应用启动信息时发生异常: {}", e.getMessage());
        }
    }

    /**
     * 屏蔽敏感信息
     * 
     * @param url 原始URL
     * @return 屏蔽后的URL
     */
    private static String maskSensitiveInfo(String url) {
        if (url == null || url.isEmpty()) {
            return url;
        }
        
        // 简单的密码屏蔽，实际项目中可以使用更复杂的正则表达式
        return url.replaceAll("password=[^&;]*", "password=***")
                  .replaceAll("pwd=[^&;]*", "pwd=***");
    }
} 